<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="名称" :label-width="labelWidth" prop="name">
        <ElInput v-model="form.name" />
      </ElFormItem>
      <el-row>
        <el-col :span="12">
          <ElFormItem label="活动种类" :label-width="labelWidth" prop="typeId">
            <el-cascader v-model="form.typeId" :options="options" :props="props" @change="handleChange" />
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="活动时间" :label-width="labelWidth" prop="holdDate">
            <el-date-picker v-model="form.holdDate" value-format="YYYY-MM-DD" />
          </ElFormItem>
        </el-col>
      </el-row>
      <ElFormItem label="活动地点" :label-width="labelWidth" prop="address">
        <ElInput v-model="form.address" />
      </ElFormItem>
      <el-row>
        <el-col :span="12">
          <ElFormItem label="经度" :label-width="labelWidth" prop="longitude">
            <ElInput v-model="form.longitude" />
          </ElFormItem>
        </el-col>
        <el-col :span="12">
          <ElFormItem label="纬度" :label-width="labelWidth" prop="latitude">
            <ElInput v-model="form.latitude" />
          </ElFormItem>
        </el-col>
      </el-row>
      <ElFormItem label="活动内容" :label-width="labelWidth" prop="content">
        <Editor v-model:value="editorValue" :style="'height: ' + editorHeight + 'px'" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance, CascaderOption } from 'element-plus'
import { FormType } from '@/enums'
import {
  ResearchActivities,
  getResearchActivitiesDetail,
  saveOrUpdateResearchActivities
} from '@api/tby/education/researchActivities'
import { TbyCategoryDict, cascaderOptionCategoryDict } from '@api/tby/common/categoryDict'
import Editor from '@/components/WangEditor/index.vue'
import { dateFormat, validateLongitude, validateLatitude } from '@api/tby/common/common'
import { ElMessage } from 'element-plus'

const editorValue = ref('')
const labelWidth = 100
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<ResearchActivities.Form>>({})
const options = ref<CascaderOption[]>([])
const editorHeight = ref(400)

const props = {
  expandTrigger: 'hover' as const
}

onMounted(async () => {
  console.log('进来了')
  let divHeight: number = document.body.clientHeight
  editorHeight.value = divHeight - 380
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

async function filterCategoryDict(category?: string) {
  let query: TbyCategoryDict.Query = {
    current: 1,
    size: 500
  }
  if (category) {
    query.category = category
  }
  const { data } = await cascaderOptionCategoryDict(query)
  options.value = data
}

const handleChange = (value: any) => {
  form.value.categoryId = value[0]
  form.value.typeId = value[1]
}

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { max: 20, message: '设备名称最大20个字符', trigger: 'blur' }
  ],
  typeId: [{ required: true, message: '请选择活动种类', trigger: 'blur' }],
  holdDate: [{ required: true, message: '请选择活动时间', trigger: 'blur' }],
  content: [{ required: true, message: '请输入活动内容', trigger: 'blur' }],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
    { max: 32, message: '经度最大32个字符', trigger: 'blur' },
    { validator: validateLongitude, trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
    { max: 32, message: '纬度最大32个字符', trigger: 'blur' },
    { validator: validateLatitude, trigger: 'blur' }
  ]
})

const open = async (type: FormType, id?: number) => {
  filterCategoryDict('activity_category')
  form.value = {
    content: '初始化'
  }
  editorValue.value = ''
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
  } else {
    try {
      const { data } = await getResearchActivitiesDetail(id!)
      loading.value = false
      form.value = data
      console.log(data)
      if (data.content) {
        editorValue.value = data.content
      }
      if (form.value.holdDate) {
        form.value.holdDate = dateFormat(parseInt(form.value.holdDate), 'yyyy-MM-dd')
      }
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
  editorValue.value = ''
  form.value = {}
}

const onSaveClicked = () => {
  if (!formRef.value) {
    return
  }
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    if (editorValue.value == '') {
      ElMessage({
        type: 'error',
        message: '请输入活动内容!'
      })
      return
    }
    const formData = { ...unref(form) }
    formData.content = editorValue.value
    saveOrUpdateResearchActivities(formData).then(() => {
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
